<?php
include("global-settings.php");
//Connect to database
mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());

// grab form data
$username 	= mysql_real_escape_string(strip_tags($_POST['username']));
$password 	= mysql_real_escape_string(strip_tags(sha1($_POST['password'])));
$first_name = mysql_real_escape_string(strip_tags($_POST['first_name']));
$last_name	= mysql_real_escape_string(strip_tags($_POST['last_name']));
$email		= mysql_real_escape_string(strip_tags($_POST['email_address']));

$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'"); 

$username_exist = mysql_num_rows($checkuser);

if($username_exist > 0){
    echo "I'm sorry but the username you specified has already been taken.  Please pick another one.";
    unset($username);
    header("Location: ../startpage.php");
    exit();
}
$userid_generator = uniqid(rand(), false);
mysql_query("INSERT INTO requests (RequestSentByID, RequestRecipientID, StatusType, AddedMessage, FriendType)
VALUES('1', '$userid_generator', 'Accepted', 'Welcome to Druvla', 'full')")or die(mysql_error());
mysql_query("INSERT INTO users (user_pid, username, password, first_name, last_name, email)
VALUES('$userid_generator', '$username', '$password', '$first_name', '$last_name', '$email')")or die(mysql_error());

if(is_dir($userid_generator)) {
echo "Something wen't wrong. A bug report has been sent and we are doing what we can to fix it.";
$message = 'Registration problem on account number $userid_generator. The user succesfully registered, but there is already
a directory with the account id of $userid_generator.';
mail($bug_report_email, "Registration Bug!", $message);
} else {
mkdir('../media/User-PID{' . $userid_generator . '}', 0777);
mkdir('../media/User-PID{' . $userid_generator . '}/photos', 0777);
mkdir('../media/User-PID{' . $userid_generator . '}/backups', 0777);
mkdir('../media/User-PID{' . $userid_generator . '}/videos', 0777);
mkdir('../media/User-PID{' . $userid_generator . '}/documents', 0777);
mkdir('../media/User-PID{' . $userid_generator . '}/developer', 0777);
mkdir('../media/User-PID{' . $userid_generator . '}/developer/apps', 0777);
mkdir('../media/User-PID{' . $userid_generator . '}/developer/themes', 0777);
mkdir('../media/User-PID{' . $userid_generator . '}/xml', 0777);
}

session_start();
$_SESSION['username'] 	  = $username;
$_SESSION['userid'] 	  = $userid_generator;
$_SESSION['first_name']   = $first_name;
$_SESSION['last_name'] 	  = $last_name;

header("Location: ../index.php");
?>